/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ProviderUI.java
 *
 * Created on May 9, 2012, 12:56:56 AM
 */

import java.rmi.RMISecurityManager;

import javax.swing.table.DefaultTableModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;

import FlexTrade.WSAdaptor;
import FlexTrade.WSAdaptorServiceLocator;
import common_classes.ProviderData;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.xml.rpc.ServiceException;

/**Cannot add
 *
 * @author hieuht
 * main user interface for provider
 */
public class ProviderUI extends javax.swing.JFrame {

	private static final long serialVersionUID = 1L;
	//Path to policy file. In order to simlify, all permissions are allowed
   
	public static String POLICY_FILE = "/home/hieuht/Eclipse/workspaceJEE/FlexTrade/src/FlexTrade/policy.txt";

    public ProviderUI() {
        initComponents();
        this.setTitle("FlexTrade Provider UI");
        this.logedIn = false;
        WSAdaptorServiceLocator locator = new WSAdaptorServiceLocator();
        try {
			service = locator.getWSAdaptor();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        btnNewAuction = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jScrollPane1.addMouseListener(new MouseAdapter() {
        	@Override
        	public void mouseClicked(MouseEvent e) {
         	}
        });
        tblActiveAuction = new javax.swing.JTable();

        jScrollPane2 = new javax.swing.JScrollPane();
        txtAuctionStates = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
         btnNewAuction.setText("New Auction");
        btnNewAuction.setName("btnNewAuction"); // NOI18N
        btnNewAuction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewAuctionActionPerformed(evt);
            }
        });

        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        jLabel1.setText("Current active auctions");

        jLabel2.setText("Auctions states log");
        this.model = new javax.swing.table.DefaultTableModel(
                new Object [][] {},
                    new String [] {
                        "ID", "Product", "Type", "Asking Price", "Status"
                    }
                );
        tblActiveAuction.setModel(model);
        tblActiveAuction.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblActiveAuctionMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblActiveAuction);

        txtAuctionStates.setColumns(20);
        txtAuctionStates.setRows(5);
        jScrollPane2.setViewportView(txtAuctionStates);
        
        btnLogIn = new JButton("Log In");
        btnLogIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLogInActionPerformed(evt);
            }
        });
        
        btnNewProvider = new JButton("New Provider");
        btnNewProvider.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewProviderActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addGap(12)
        			.addComponent(jLabel1))
        		.addGroup(layout.createSequentialGroup()
        			.addGap(10)
        			.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 680, GroupLayout.PREFERRED_SIZE))
        		.addGroup(layout.createSequentialGroup()
        			.addGap(12)
        			.addComponent(jLabel2))
        		.addGroup(layout.createSequentialGroup()
        			.addGap(10)
        			.addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 680, GroupLayout.PREFERRED_SIZE))
        		.addGroup(layout.createSequentialGroup()
        			.addGap(40)
        			.addComponent(btnLogIn, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE)
        			.addGap(74)
        			.addComponent(btnNewProvider)
        			.addGap(52)
        			.addComponent(btnNewAuction)
        			.addGap(41)
        			.addComponent(btnExit, GroupLayout.PREFERRED_SIZE, 101, GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addGap(23)
        			.addComponent(jLabel1)
        			.addGap(19)
        			.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 140, GroupLayout.PREFERRED_SIZE)
        			.addGap(16)
        			.addComponent(jLabel2)
        			.addGap(16)
        			.addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 140, GroupLayout.PREFERRED_SIZE)
        			.addGap(19)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(btnLogIn)
        				.addComponent(btnExit)
        				.addComponent(btnNewAuction)
        				.addComponent(btnNewProvider))
        			.addGap(34))
        );
        getContentPane().setLayout(layout);

        pack();
    }// </editor-fold>

    private void btnNewAuctionActionPerformed(java.awt.event.ActionEvent evt) { 
    	/*if(!this.logedIn) {
    		JOptionPane.showMessageDialog(null, "You have to login before using this function.");
    		return;
    	}*/
        // TODO add your handling code here:
    	//Create new Provider object. 
    	//Each auction requested by Provider is correspond to 01 provider object
        //provider = new Provider();
        //Auctions status will be shown in text field txtAuctionStates of main UI
        //provider.setTextField(this.txtAuctionStates);
        //provider.setTableModel(this.model);
        //pop up NewAuctionDlg form
        NewAuctionDlg newAuction = new NewAuctionDlg(this, true);
        newAuction.setProviderData(this.providerData);		//transfer providerData to NewAuctionDlg from
        //provider object and table model object are shared between main UI and NewAuctionDlg form
        //newAuction.setProvider(provider);
        newAuction.setService(service);
        newAuction.setVisible(true);
    }                                             

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    	eventThread.stopEventThread();
        System.exit(1);
    }
    
    private void btnLogInActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    	if(this.logedIn) {
    		JOptionPane.showMessageDialog(null, "You are already logged in.");
    		return;
    	}
        LogInDlg loginDlg = new LogInDlg(this, true);
        loginDlg.setService(service);
        loginDlg.setVisible(true);
    }
    
    private void btnNewProviderActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        CreateProvider createProvider = new CreateProvider(this, true);
        createProvider.setService(service);
        createProvider.setVisible(true);
    }
    
    private void tblActiveAuctionMouseClicked(java.awt.event.MouseEvent evt) {
        // TODO add your handling code here:
    	if(!this.logedIn) {		//do nothing when provider has not logged in yet
    		return;
    	}
    	
    	int selectedRow = tblActiveAuction.getSelectedRow();
    	//get the auction ID and aution type of selected item in table (column 0 and 2)
		String selectedUniqueAuctionID = (String)tblActiveAuction.getValueAt(selectedRow, 0);
		String strSelectedAuctionType = (String)tblActiveAuction.getValueAt(selectedRow, 2);
		if(strSelectedAuctionType.equals("Dutch")){ 	//if Dutch auction type
			//pop up DutchStateDlg
			DutchStatesDlg dutchStatesDlg = new DutchStatesDlg(this, true);
			dutchStatesDlg.setService(service);
			dutchStatesDlg.setUniqueAuctionID(selectedUniqueAuctionID);
			dutchStatesDlg.setVisible(true);
		} else {		//if Vickrey or English auction
			//pop up OtherStatesDlg
			OtherStatesDlg otherStatesDlg = new OtherStatesDlg(this, true);
			otherStatesDlg.setService(service);
			otherStatesDlg.setUniqueAuctionID(selectedUniqueAuctionID);
			otherStatesDlg.setVisible(true);
		}
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        //Set security manager
        /*System.setProperty("java.security.policy",POLICY_FILE);
        System.setSecurityManager(new RMISecurityManager());
		System.setProperty("java.rmi.server.codebase", "http://localhost:9000/");*/
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ProviderUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ProviderUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ProviderUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ProviderUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ProviderUI().setVisible(true);
            }
        });
    }
    
    public Provider getProvider() {
    	//return provider;
    	return null;
    }
    
    public void setProviderData(ProviderData _providerData){
    	this.providerData = _providerData;
    	eventThread.setProviderData(_providerData);
    	eventThread.setService(service);
    	eventThread.setTextField(txtAuctionStates);
    	runThread.start();
    }
    
    public ProviderData getProviderData(){
    	return this.providerData;
    }
    // Variables declaration - do not modify
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnNewAuction;
    private javax.swing.JButton btnNewProvider;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    public javax.swing.JTable tblActiveAuction;
    private javax.swing.JTextArea txtAuctionStates;
    private JButton btnLogIn;
    // End of variables declaration
     //public Provider provider = null;
     DefaultTableModel model;
     public boolean logedIn;
     ProviderData providerData;
     WSAdaptor service;
     Provider eventThread = new Provider();
     Thread runThread = new Thread(eventThread, "EventThread");
}
